package com.ddl.kafka.controller;

import com.ddl.kafka.config.producer.Demo01Producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class MsgRest {

	@Autowired
	private Demo01Producer demo01Producer;

	@GetMapping("sendMsg")
	public void sendMsg() throws Exception {
		int id = (int) (System.currentTimeMillis() / 1000);
		SendResult result = demo01Producer.syncSend((long) id);
		log.info("[testSyncSend][发送编号：[{}] 发送结果：[{}]]", id, result);

		// 阻塞等待，保证消费
		new CountDownLatch(1).await();
	}

	@GetMapping("sendMsg1")
	public void sendMsg1() throws Exception {
		int id = (int) (System.currentTimeMillis() / 1000);
		demo01Producer.asyncSend((long) id).addCallback(new ListenableFutureCallback<SendResult<Object, Object>>() {

			@Override
			public void onFailure(Throwable e) {
				log.info("[testASyncSend][发送编号：[{}] 发送异常]]", id, e);
			}

			@Override
			public void onSuccess(SendResult<Object, Object> result) {
				log.info("[testASyncSend][发送编号：[{}] 发送成功，结果为：[{}]]", id, result);
			}

		});

		// 阻塞等待，保证消费
		new CountDownLatch(1).await();
	}
}
